<template>
  <div class="app-container">
    <div class="title-backgroud">
      <span style="font-size: 20px;color: #00afff; "><b>查看详情</b></span>
    </div>
    <!--    <div style="border: 1px solid #2C8DEB;text-align: center;color: #2C8DEB; margin: 20px;-->
    <!--    border-radius: 5px;padding: 5px 8px;width: 80px;font-size: 16px;cursor: pointer;" @click="closePage">-->
    <!--      返回-->
    <!--    </div>-->
    <el-button type="primary" size="mini" style="width: 60px;margin-left: 20px;margin-top: 20px;margin-bottom: 20px;"
               @click="closePage">返回
    </el-button>
    <div style="margin-left: 20px;">
      <el-row>
        <el-col :span="12"><label><span style="font-size: 20px;">{{ schoolName }}——{{ lineName }}</span></label>
        </el-col>
      </el-row>
      <el-row style="margin: 5px 0;">
        <el-col :span="12"><span style="font-size: 16px;">状态：
          <span v-if="abnormalCount==0" style="color: #07A387;">正常</span>
          <span v-else-if="abnormalCount>0" style="color: #E94242;">{{ abnormalCount }}项异常({{ abnormalSites }})</span>
        </span></el-col>
      </el-row>
      <el-row style="font-size: 14px; margin: 5px 0;">
        <span style="margin-right: 40px;">人员(小组)：{{ groupName }}</span>
        <span>巡查时间：{{ date }}</span>
      </el-row>
    </div>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="12">
        <div class="block">
          <el-scrollbar style="height: 600px">
            <el-timeline style="height: 600px;margin-top: 20px">
              <el-timeline-item
                v-for="(detail, index) in recordDetailList"
                :key="index"
                color="#1E8BFC"
                hide-timestamp
                :timestamp="detail.updateTime">
                <el-row style="margin-bottom: 5px;">
                  <el-col :span="24" style="font-size: 14px;">
                  <span style="margin-right: 40px;"
                        v-if="detail.state!=-1">{{ detail.updateTime.substring(11, 16) }}</span>
                    <span style="margin-right: 40px;">{{ "打卡点位：" + (detail.index) }}</span>
                    <span style="margin-right: 40px;">{{ detail.siteName }}</span>
                    <span style="margin-right: 40px;"><span>状态：</span><span v-if="detail.state==0"
                                                                            style="color: #07A387;">正常</span>
                <span style="color: #E94242;" v-else-if="detail.state==1 || detail.state==2">异常</span>
                <span v-if="detail.state==2">(已处理<span
                  v-if="detail.handleInfo!=null&&detail.handleInfo!=''">， 处理结果：{{
                    detail.handleInfo
                  }}</span>)</span><span
                        v-else-if="detail.state==-1">未巡查</span>
              </span>
                    <span style="margin-right: 40px;"><span
                      v-if="detail.state!=-1">巡查人员：</span>{{ detail.updateBy }}</span>
                    <span v-if="detail.state==1 || detail.state==2" style="margin-right: 40px;">原因：<span
                      style="color: #E94242;">{{ detail.remark }}</span></span>
                    <el-button v-if="detail.state==1 && isSchoolRole" size="mini" type="success"
                               @click="handleAbnormal(detail)">处理
                    </el-button>
                  </el-col>
                </el-row>
                <el-row style="margin-bottom: 5px;">
                  <el-image v-if="detail.photoUrl != null"
                            style="width: 90px; height: 90px; border-radius: 10px;"
                            :src="detail.photoUrl"
                            :preview-src-list="srcList">
                  </el-image>
                  <el-image v-else-if="detail.photoUrl == null"
                            style="width: 90px; height: 90px; border-radius: 10px;"
                            :src="require('@/assets/patrol.png')">
                  </el-image>
                </el-row>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="12">
        <div id="container"/>
      </el-col>
    </el-row>

    <el-dialog title="异常处理" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" @submit.native.prevent
               @keyup.enter.native="addHandleInfo">
        <el-form-item label="处理结果" prop="handleInfo">
          <el-input maxlength="200" type="textarea" autosize v-model="form.handleInfo"
                    placeholder="请输入200个以内的数字/常用文字/中文符号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addHandleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDetail, updateDetail} from "@/api/patrol/line_record_detail";
import {parseTime} from "@/utils/ruoyi";
import AMapLoader from "@amap/amap-jsapi-loader";
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '47f39bbd3f47b91d1cbb2311453a0b4e',
}
export default {
  name: "Guard",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡查线路与安保人员关联表格数据
      recordDetailList: [],
      srcList: [],
      record: {},
      lineName: "",
      schoolName: "",
      groupName: "",
      date: "",
      abnormalCount: 0,
      abnormalSites: "",
      form: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      rules: {
        handleInfo: [
          {
            pattern: /^((\w|[\u4E00-\u9FFF]|[\u3000-\u301e\ufe10-\ufe19\ufe30-\ufe44\ufe50-\ufe6b\uff01-\uffee]){0,200})$/,
            message: "请输入200个以内的数字/常用文字/中文符号"
          }
        ],
      },
      // 地图相关
      map: null,
      marker: null,
      gps: {
        name: [],
        itme: [],
        dian: []
      },
    };
  },
  computed: {
    isSchoolRole() {
      return this.$store.getters.type === "school";
    },
  },
  created() {
    this.queryParams.scheduleId = this.$route.query && this.$route.query.scheduleId;
    this.lineName = this.$route.query && this.$route.query.lineName;
    this.schoolName = this.$route.query && this.$route.query.schoolName;
    this.date = this.$route.query && this.$route.query.date;
    this.groupName = this.$route.query && (this.$route.query.groupName || this.$route.query.memberName);
    this.getList();
  },
  methods: {
    /** 查询巡查线路与安保人员关联列表 */
    getList() {
      this.loading = true;
      listDetail(this.queryParams).then(response => {
        this.recordDetailList = response.data;
        let hastim = []
        let notime = []
        this.recordDetailList.forEach((e, i) => {
          this.recordDetailList[i].index = i+1
          // console.log(e)
          this.srcList.push(e.photoUrl);
          if (e.state !== -1) {
            this.gps.dian.push([parseFloat(e.longitude), parseFloat(e.latitude)]);
            this.gps.name.push(e.siteName);
            this.gps.itme.push(i + 1);
          }
          if (e.state == 1) {
            this.abnormalCount++;
            this.abnormalSites += e.siteName + "、";
          }
          if (e.updateTime){
            hastim.push(e)
          }else {
            notime.push(e)
          }
        })

        if (this.abnormalSites.length > 1) {
          this.abnormalSites = this.abnormalSites.substring(0, this.abnormalSites.length - 1);
        }
        console.log(hastim)
        console.log(notime)

        hastim.sort((a,b)=>{ return Date.parse(a.updateTime)-Date.parse(b.updateTime)})
        if (notime){
          hastim.push(...notime)
        }
        this.recordDetailList = hastim
        console.log("aaa", this.recordDetailList)
        this.record.user = this.recordDetailList[0].updateBy;
        this.record.date = parseTime(this.recordDetailList[0].updateTime, '{y}-{m}-{d}');
        console.log(this.gps)
        this.initMap()
        this.loading = false;
      });
    },
    handleAbnormal(detail) {
      this.form = detail;
      this.open = true;
    },
    cancel() {
      this.open = false;
      this.resetForm("form");
      this.form = {};
    },
    addHandleInfo() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.state = 2 //状态改为已处理
          updateDetail(this.form).then(response => {
            this.open = false;
            this.msgSuccess("处理成功");
            this.reset();
            this.getList();
            this.form = {};
          });
        }
      });
    },
    reset() {
      this.recordDetailList = [];
      this.srcList = [];
      this.record = {};
      this.abnormalCount = 0;
      this.abnormalSites = "";
    },

    closePage() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1);
      // this.$tab.openPage("安保记录", "/patrol/line_record");
    },
    initMap(lng, lat) {
      AMapLoader.load({
        "key": "a423874b07f076758138f4d36f6f74df",
        "version": "2.0",
        "plugins": [
          "AMap.Scale",
          "AMap.HawkEye",
          'AMap.MapType',
        ]
      }).then((AMap) => {
        // 初始化地图
        this.map = new AMap.Map('container', {
          viewMode: "2D",
          zoom: 13,
          // 江北区人民政府
          // center: [106.580323, 29.612549],
          center: this.gps.dian[0],
          resizeEnable: true
        });
        if (lng && lat) {
          this.map.setCenter([lng, lat], false, 100);
          this.marker = new AMap.Marker({
            position: [lng, lat]
          });
          this.map.add(this.marker);
          this.map.add(this.circle);
        }
        this.map.addControl(new AMap.MapType({defaultType: 1}));
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.HawkEye({
          isOpen: true
        }));
        var lnglats = this.gps.dian;
        var markers = [];
        for (var i = 0; i < lnglats.length; i++) {
          var lnglat = lnglats[i];
          // 创建点实例
          // var marker = new AMap.Marker({
          //   position: new AMap.LngLat(lnglat[0], lnglat[1]),
          //   icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (i + 1) + '.png',
          //   extData: {
          //     id: i + 1
          //   }
          // });
          var markerContent = '' +
            '<div class="custom-content-marker" style="text-align: center;width: 30px;height: 30px; background-size: 100% 100%;background-image: url(\'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png\')">' +
            '<span style="color: white">' + this.gps.itme[i] + '</span>' +
            '</div>';

          var marker = new AMap.Marker({
            position: new AMap.LngLat(lnglat[0], lnglat[1]),
            // 将 html 传给 content
            content: markerContent,
            // 以 icon 的 [center bottom] 为原点
            offset: new AMap.Pixel(-13, -30)
          });
          var div = "<div className='info'>" + this.gps.name[i] + "</div>";
          marker.setLabel({
            direction: 'right',
            offset: new AMap.Pixel(-1, 0),  //设置文本标注偏移量
            content: div, //设置文本标注内容
          });
          markers.push(marker);
        }
        var overlayGroups = new AMap.OverlayGroup(markers);
        this.map.add(overlayGroups);
        // this.map.on('click', this.addMarker);
        // this.searchMap();
        this.map.setFitView(null, false, [150, 60, 100, 60]);
      }).catch(e => {
        console.log(e);
      });
    },
  }
};
</script>
<style lang="scss" scoped>
#container {
  overflow: hidden;
  width: 100%;
  height: 600px;
  margin: 0;
  font-family: "微软雅黑";
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}

.title-backgroud {
  background-color: #edf1f2;
  padding: 25px 10px 35px 20px;
  height: 40px;
}

</style>

<style>
.amap-marker-label {
  border: 0;
  background-color: transparent;
}

.el-image-viewer__img {
  max-height: 80% !important;
}
</style>
